<template>
  <component
    is="a-modal"
    v-model:visible="visible"
    :width="1200"
    :title="title"
    :mask-closable="false"
    :ok-loading="loading"
    @cancel="close"
    @before-ok="submit">
    <!-- 表单信息 start -->
    <a-form ref="formRef" :model="formData" :rules="rules" :auto-label-width="true">
		<a-form-item label="职位名称" field="position_name">
		  <a-input v-model="formData.position_name" placeholder="请输入职位名称" />
		</a-form-item>
    
     
	  <a-form-item label="招聘企业" field="enterprise_id">
	  		  <a-select
	  		    v-model="formData.enterprise_id"
	  		    :options="enterpriseId"        
	  		    allow-clear
	  		    placeholder="请选择招聘企业" />
	  </a-form-item>
      
	  <a-form-item label="工作省" field="province_id">
	    <a-select
	      v-model="formData.province_id"
	      :options="provinceOptions"
	      allow-clear
	      placeholder="请选择工作省"
	      @change="handleProvinceChange"
	    />
	  </a-form-item>
	  <a-form-item label="工作城市" field="city_id">
	    <a-select
	      v-model="formData.city_id"
	      :options="cityOptions"
	      allow-clear
	      placeholder="请选择工作城市"
	      :disabled="!formData.province_id"
	      @change="handleCityChange"
	    />
	  </a-form-item>
	  <a-form-item label="工作区域" field="district_id">
	    <a-select
	      v-model="formData.district_id"
	      :options="districtOptions"
	      allow-clear
	      placeholder="请选择工作区"
	      :disabled="!formData.city_id"
	    />
	  </a-form-item>
	  <a-form-item label="学历要求" field="education_requirement">
	  		  <a-select
	  		    v-model="formData.education_requirement"
	  		    :options="educationRequirementData"        
	  		    allow-clear
	  		    placeholder="请输入学历要求" />
	  </a-form-item>
	  <a-form-item label="薪资范围" field="salary_range">
	  		  <a-select
	  		    v-model="formData.salary_range"
	  		    :options="salaryRangeData"        
	  		    allow-clear
	  		    placeholder="请选择薪资范围" />
	    
	  </a-form-item>
      <a-form-item label="工作经验年限" field="work_experience">
		  <a-select
		    v-model="formData.work_experience"
		    :options="workExperienceData"        
		    allow-clear
		    placeholder="请选择工作年限" />
      </a-form-item>
      <a-form-item label="发布日期" field="release_date">
			 <a-date-picker v-model="formData.release_date" :show-time="true" mode="date" placeholder="请输入发布日期" />
      </a-form-item>
      <a-form-item label="招聘人数" field="recruitment_number">
        <a-input v-model="formData.recruitment_number" placeholder="请输入招聘人数" />
      </a-form-item>
      <a-form-item label="展示/下架" field="is_display">
      			   <sa-switch v-model="formData.is_display" checkedText="是"  uncheckedText="否"/>
      </a-form-item>
      <a-form-item label="排序" field="sort_order">
      			<a-input-number v-model="formData.sort_order" placeholder="请输入排序" />
      		  </a-form-item>
     
      <a-form-item label="职位描述" field="position_description">
        <ma-wangEditor v-model="formData.position_description" :height="400" />
      </a-form-item>
	 
		
    </a-form>
    <!-- 表单信息 end -->
  </component>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
import api from '../api/recruitment'
import commonApi from '@/api/common'

const emit = defineEmits(['success'])
// 引用定义
const visible = ref(false)
const loading = ref(false)
const formRef = ref()
const mode = ref('')
const provinceOptions = ref([])
const cityOptions = ref([])
const districtOptions = ref([])
const workExperienceData=ref([])
const salaryRangeData=ref([])
const educationRequirementData=ref([])
const enterpriseId=ref([])
let title = computed(() => {
  return '招聘列表' + (mode.value == 'add' ? '-新增' : '-编辑')
})

// 表单信息
const formData = reactive({
  recruitment_id: null,
  lang_code: '',
  sort_order: 0,
  enterprise_id: '',
  salary_range: '',
  province_id: 0,
  city_id: 0,
  district_id: 0,
  release_date: '',
  recruitment_number: null,
  position_name: '',
  education_requirement: '',
  position_description: '',
  is_display: 0,
})

// 验证规则
const rules = {
  lang_code: [{ required: true, message: '语言代码，如zh - CN、en - US等必需填写' }],
  enterprise_id: [{ required: true, message: '招聘企业必需填写' }],
  position_name: [{ required: true, message: '职位名称必需填写' }],
}

// 打开弹框
const open = async (type = 'add') => {
  mode.value = type
  visible.value = true
  formRef.value.resetFields()
  await initPage()
}

// 初始化页面数据
const initPage = async () => {
	
	const workExperience = await commonApi.commonGet('/cassification/ClassificationDictionary/getCate',{classification_type:11})
	workExperienceData.value = workExperience.data
	const salaryRange = await commonApi.commonGet('/cassification/ClassificationDictionary/getCate',{classification_type:13})
	salaryRangeData.value = salaryRange.data
	const educationRequirement = await commonApi.commonGet('/cassification/ClassificationDictionary/getCate',{classification_type:12})
	educationRequirementData.value = educationRequirement.data
	const enterpriseIdData= await commonApi.commonGet('/recruitmentEnterprise/recruitmentEnterprise/getSelect',{lang_code:formData.lang_code})
	enterpriseId.value = enterpriseIdData.data

}

// 设置数据

// 加载省份数据
const loadProvinces = async () => {
  const resp = await commonApi.commonGet('/Cnarea/Cnarea/getSelect',{level:1}) // 替换为实际获取省份的 API 地址
  provinceOptions.value = resp.data.map(item => ({
    value: item.value,
    label: item.label
  }))
}

// 加载城市数据
const loadCities = async (provinceId) => {
  const resp = await commonApi.commonGet('/Cnarea/Cnarea/getSelect', {level:2,parent_code:provinceId }) // 替换为实际获取城市的 API 地址
  cityOptions.value = resp.data.map(item => ({
   value: item.value,
   label: item.label
  }))
  // 清空市选择后，同时清空区选择
  formData.city_id = 0
  formData.district_id = 0
  // districtOptions.value = []
}

// 加载区县数据
const loadDistricts = async (cityId) => {
  const resp = await commonApi.commonGet('/Cnarea/Cnarea/getSelect', { level:3,parent_code:cityId }) // 替换为实际获取区县的 API 地址
  districtOptions.value = resp.data.map(item => ({
   value: item.value,
   label: item.label
  }))
  formData.district_id = 0
}

// 省选择变化处理
const handleProvinceChange = async (provinceId) => {
  if (provinceId) {
    await loadCities(provinceId)
  } else {
    formData.city_id = 0
    formData.district_id = 0
  }
}

// 市选择变化处理
const handleCityChange = async (cityId) => {
  if (cityId) {
    await loadDistricts(cityId)
  } else {
    // districtOptions.value = []
    formData.district_id = 0
  }
}

// 设置数据
const setFormData = async (data) => {
  for (const key in formData) {
    if (data[key] != null && data[key] != undefined) {
      formData[key] = data[key]
    }
  }
  // 若有省市区数据，重新加载对应数据
  await loadProvinces()
  // 若有省市区数据，重新加载对应数据
  if (data.province_id!=='') {
    await loadCities(data.province_id)
    if (data.city_id!=='') {
      await loadDistricts(data.city_id)
    }
  }
}

// 数据保存
const submit = async (done) => {
  const validate = await formRef.value?.validate()
  if (!validate) {
    loading.value = true
    let data = { ...formData }
    let result = {}
    if (mode.value === 'add') {
      // 添加数据
      data.recruitment_id = undefined
      result = await api.save(data)
    } else {
      // 修改数据
      result = await api.update(data.recruitment_id, data)
    }
    if (result.code === 200) {
      Message.success('操作成功')
      emit('success')
      done(true)
    }
    // 防止连续点击提交
    setTimeout(() => {
      loading.value = false
    }, 500)
  }
  done(false)
}

// 关闭弹窗
const close = () => (visible.value = false)

defineExpose({ open, setFormData })
</script>
